#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <net/if.h>


int main(void)
{
    struct sockaddr_can can_addr = {0};
    struct ifreq ifr = {0};
    struct can_frame frame = {0};
    int sockfd = -1;
    int ret;

    sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (sockfd < 0) {
        printf("socket error\n");
        exit(EXIT_FAILURE);
    }

    strcpy(ifr.ifr_name, "can0");
    ioctl(sockfd, SIOCGIFINDEX, &ifr);
    can_addr.can_family = AF_CAN;
    can_addr.can_ifindex = ifr.ifr_ifindex;

    ret = bind(sockfd, (struct sockaddr *)&can_addr, sizeof(can_addr));
    if (ret < 0) {
        printf("bind error\n");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    setsockopt(sockfd, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);   // 不接收任何数据

    frame.can_id = 0x123;
    frame.can_dlc = 6;
    frame.data[0] = 0xA0;
    frame.data[1] = 0xB0;
    frame.data[2] = 0xC0;
    frame.data[3] = 0xD0;
    frame.data[4] = 0xE0;
    frame.data[5] = 0xF0;

    while(1) {
        ret = write(sockfd, &frame, sizeof(frame));
        if (ret != sizeof(frame)) {
            printf("write error\n");
            goto out;
        }

        sleep(1);
    }

out: 
    close(sockfd);
    exit(EXIT_SUCCESS);
}
